package com.qf58.search.commons;

import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;

import java.net.InetAddress;

/**
 * Created with IntelliJ IDEA.
 * Description: ES服务器链接工具类
 * User: zhubo
 * Date: 2017-08-29
 * Time: 16:02
 */
public class ESConnect {

    private TransportClient transportClient;

    private static ESConnect clientInstance;

    /**
     * client.transport.sniff为true来使客户端去嗅探整个集群的状态，把集群中其它机器的ip地址加到客户端中，这样做的好处是一般你不用手动设置集群里所有集群的ip到连接客户端，它会自动帮你添加，并且自动发现新加入集群的机器
     * @throws Exception
     */
    private ESConnect() throws Exception{
        Settings settings = Settings.builder()
                .put("cluster.name", IndexConfig.clusterName)
                .put("client.transport.ignore_cluster_name", true)
                .put("client.transport.sniff", true).build();
        transportClient = new PreBuiltTransportClient(settings)
                .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(IndexConfig.domainName1), Integer.parseInt(IndexConfig.connectPort1)));
    }

    public static ESConnect getInstance()throws Exception{
        if(clientInstance == null){
            clientInstance = new ESConnect();
        }
        return clientInstance;
    }

    public TransportClient getTransportClient(){
        return transportClient;
    }

    public static void closeClient(TransportClient client){
        if(client != null){
            //TODO 因为单例模式 所以无需关闭
            //client.close();
        }
    }
}
